import React, { Component } from 'react'
import styles from './index.module.scss'
import { SearchBar } from 'antd-mobile'
import { getCurrentCity } from '../../../utils/city'
import { getCommunityList } from '../../../api/rent'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
// import { setCommunity } from '../../../store/actionCreator'
import * as actionCreator from '../../../store/actionCreator'
class RentSearch extends Component {
    state = {
        communityList: null
    }
    // 输入框内容防抖
    debounce = (fun, delay) => {
        return function (args) {
            //获取函数的作用域和变量
            let that = this
            let _args = args
            //每次事件被触发，都会清除当前的timeer，然后重写设置超时调用
            clearTimeout(fun.id)
            fun.id = setTimeout(function () {
                fun.call(that, _args)
            }, delay)
        }
    }
    componentDidMount() {
        this.debounceSearch = this.debounce(this.search, 500)
    }
    onChange = (val) => {
        // console.log(val)
        this.debounceSearch(val)
    }
    // 搜索建议
    search = async (name) => {
        // console.log(val)
        const { value: id } = await getCurrentCity()
        const res = await getCommunityList(id, name)
        this.setState({
            communityList: res.data.body
        })
    }
    toggleSelect = ({ community, communityName }) => {
        console.log(community, communityName)
        // this.props.setCommunityData({ community, communityName })
        this.props.setCommunity({ community, communityName })
        this.props.history.goBack()
    }
    render() {
        const { communityList } = this.state
        return (
            <div className={styles.root}>
                <SearchBar onChange={this.onChange} onCancel={() => this.props.history.goBack()} placeholder='请输入小区或地址' />
                {communityList && (
                    <ul className={styles.tips}>
                        {communityList.map(item => {
                            return <li onClick={() => this.toggleSelect(item)} key={item.community} className={styles.tip}>{item.communityName}</li>
                        })}
                    </ul>
                )}
            </div>
        )
    }
}
const mapDispatchToProps = (dispatch) => {
    // return {
    //     setCommunityData: function (obj) {
    //         dispatch(setCommunity(obj))
    //     }
    // }
    return bindActionCreators(actionCreator, dispatch)
}
export default connect(null, mapDispatchToProps)(RentSearch)
